package com.example.base.security.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.base.security.SecurityUtil;
import com.example.base.security.domain.SelfUserEntity;
import com.example.base.security.domain.SysUserEntity;
import com.example.base.security.domain.SysUserToken;
import com.example.base.security.jwt.JWTConfig;
import com.example.base.security.jwt.JWTTokenUtil;
import com.example.base.security.service.LoginService;
import com.example.base.security.service.SysUserTokenService;
import com.example.base.utils.ResponseUtils;
import com.example.base.utils.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public void loginSuccess(HttpServletResponse response, Authentication authentication) {
        // 组装JWT
        SysUserEntity selfUserEntity =  (SysUserEntity) authentication.getPrincipal();

        SelfUserEntity selfuser=new SelfUserEntity();
        BeanUtils.copyProperties(selfUserEntity,selfuser);

        String token = JWTTokenUtil.createAccessToken(selfuser);
        token = JWTConfig.tokenPrefix + token;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code",200);
        resultData.put("message", "登录成功");
        JSONObject data=new JSONObject();
        data.put("token",token);
        JSONObject userInfo=new JSONObject();
        data.put("userInfo",userInfo);
        userInfo.put("userId",selfUserEntity.getUserId());
        userInfo.put("userName",selfUserEntity.getUsername());
        userInfo.put("dashboard","0");

        JSONArray roleList=new JSONArray();
        roleList.add("admin");
        roleList.add("SA");
        roleList.add("Auditor");
        userInfo.put("role",roleList);

        resultData.put("data",data);
        Cookie cookie = new Cookie(JWTConfig.tokenHeader, token);

        Claims claims=JWTTokenUtil.getClaimsByToken(token);
        SysUserToken sysUserToken=new SysUserToken();
        sysUserToken.setToken(token);
        sysUserToken.setIsDisabled(true);
        sysUserToken.setLogindate(new Date());
        sysUserToken.setUsername(selfUserEntity.getUsername());
        sysUserToken.setUserid(selfUserEntity.getUserId().toString());
        sysUserToken.setIsEnable(true);
        sysUserToken.setExpiryDate(claims.getExpiration());
        sysUserTokenService.save(sysUserToken);

        // 设置Cookie的其他属性（可选）
        cookie.setMaxAge(3600); // 设置Cookie的生命周期，单位为秒
        cookie.setPath("/"); // 设置Cookie的路径
        // 其他属性，如：cookie.setDomain("domain.com");
        // 将Cookie添加到响应中
        response.addCookie(cookie);
        ResponseUtils.responseJson(response,resultData);
    }

    @Override
    public void loginFail(AuthenticationException exception,HttpServletResponse response) {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException){
            log.info("【登录失败】"+exception.getMessage());
            ResponseUtils.responseJson(response, Result.msg(500,"用户名不存在"));
        }
        if (exception instanceof LockedException){
            log.info("【登录失败】"+exception.getMessage());
            ResponseUtils.responseJson(response, Result.msg(500,"用户被冻结"));
        }
        if (exception instanceof BadCredentialsException){
            log.info("【登录失败】"+exception.getMessage());
            ResponseUtils.responseJson(response, Result.msg(500,exception.getMessage()));
        }
        ResponseUtils.responseJson(response, Result.msg(500,"登录失败"));
    }

    @Override
    public void loginOutSucess(HttpServletRequest request,HttpServletResponse response) {
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code",200);
        resultData.put("msg", "登出成功");
        SecurityContextHolder.clearContext();
        String tokenHeader = request.getHeader(JWTConfig.tokenHeader);
        log.info("token:{}",tokenHeader);
        sysUserTokenService.removTokenByToken(tokenHeader);
        ResponseUtils.responseJson(response,resultData);
        SecurityUtil.getSysUserEntity();
    }
}
